<#import "../common/mymacros.ftl" as mymacro>

<form action="${ctx}/company/form" method="post" id="addCompany" enctype="multipart/form-data">
		<input type="hidden" name="companyId" value="${company.companyId!}" />
		<input type="hidden" name="userId" value="${user.userId!}" />
		<div class="form-group form-inline row">
			<div class="col-sm-6">
				<label><span style="color: red">*</span>公司名称：</label>
				<input class="form-control" type="text" name="companyName" value="${company.companyName!}" maxlength="100"  required />
			</div>
			<div class="col-sm-6">
				<label><span style="color: red">*</span>公司简称：</label>
				<input class="form-control" type="text" name="shortName" value="${company.shortName!}" maxlength="50"  required />
			</div>
		</div>
		<div class="form-group form-inline row">
			<div class="col-sm-6">
				<div style="display: inline-block;">
					<label><span style="color: red">*</span>所属地区：</label>
					<select class="form-control select2" name="provinceCode"  style="width: 120px;" >
						<option value="">--请选择--</option>
						<#list firstLevel as a>
							<option value="${a.code}" <#if company.provinceCode?? && a.code==company.provinceCode>selected</#if> >${a.city}</option>
						</#list>
					</select>
				</div>
				<select class="form-control select2" name="cityCode" id="cityCodeForm" style="width: 120px" required>
					<option value="">--请选择--</option>
					<#if secondLevel??>
						<#list secondLevel as a>
							<option value="${a.code}" <#if company.cityCode?? && a.code==company.cityCode>selected</#if> >${a.city}</option>
						</#list>
					</#if>
				</select>
			</div>
			<div class="col-sm-6">
				<label><span style="color: red">*</span>所属行业:</label>
				<select class="form-control" name="industryId"  required>
					<option value="">--请选择--</option>
					<#list industryMap as k,v>
						<option value="${k}" <#if company.industryId?? && k == company.industryId?c >selected</#if> >${v}</option>
					</#list>
				</select>
			</div>
		</div>
		<div class="form-group form-inline row">
			<div class="col-sm-6">
				<label>销售：</label>
				<#if userType == 1 || userType == 2>
					<input class="form-control" type="hidden" name="saleId" value="${loginUser.agentSaleId!}" />
					<input class="form-control" type="text" name="saleName" value="${loginUser.agentSaleName!}" readonly="readonly" />
				<#else>
					<select class="form-control select2" name="saleId">
						<option value="">--请选择--</option>
						<#list saleManagers as sale>
							<option value="${sale.id}" <#if company.saleId?? && sale.id == company.saleId>selected</#if> >${sale.nickName!}</option>
						</#list>
					</select>
					<input class="form-control" type="hidden" name="saleName" value="${company.saleName!}" />
				</#if>
			</div>
			<div class="col-sm-6">
				<label>客户经理：</label>
				<#if userType == 1 || userType == 2>
					<input class="form-control" type="hidden" name="accountManagerId" value="${loginUser.accountManagerId!}" />
					<input class="form-control" type="text" name="accountManagerName" value="${loginUser.accountManagerName!}" readonly="readonly" />
				<#else>
					<select class="form-control select2" name="accountManagerId">
						<option value="-1">--请选择--</option>
						<#list accountManages as accountManage>
							<option value="${accountManage.id!}" <#if company.accountManagerId?? && accountManage.id == company.accountManagerId>selected</#if> >${accountManage.nickName!}</option>
						</#list>
					</select>
					<input class="form-control" type="hidden" name="accountManagerName" value="${company.accountManagerName!}" />
				</#if>
			</div>
		</div>
		<div class="form-group form-inline row">
			<div class="col-sm-6">
				<label><span style="color: red">*</span>代理商：</label>
				<#if userType == 1>
					<input class="form-control" type="hidden" name="agentsId" value="${agents[0].id!}" />
					<input class="form-control" type="text" name="agentsName" value="${agents[0].nickName!}" readonly="readonly" />
				<#else>
					<select class="form-control select2" name="agentsId" required>
						<option value="">--请选择--</option>
						<#if agents?? && (agents?size > 0)>
						<#list agents as u>
	                       <option value="${u.id}" <#if company.agentsId?? && u.id==company.agentsId>selected</#if> >${u.nickName!}</option>
	                   </#list>
	                   </#if>
					</select>
					<input type="hidden" name="agentsName" value="${company.agentsName!}" />
				</#if>
			</div>
			<div class="col-sm-6">
				<label>启用状态：</label>
				<#if company.enableStatus??>
					<label class="radio-inline"><input type="radio" class="minimal" name="enableStatus"  value="1" <#if company?? && company.enableStatus?? && company.enableStatus = 1>checked</#if> >&nbsp;&nbsp;启用</label>
					<label class="radio-inline"><input type="radio" class="minimal" name="enableStatus"  value="0" <#if company?? && company.enableStatus?? && company.enableStatus = 0>checked</#if> >&nbsp;&nbsp;停用</label>
				<#else>
					<label class="radio-inline"><input type="radio" class="minimal" name="enableStatus"  value="1" checked >&nbsp;&nbsp;启用</label>
					<label class="radio-inline"><input type="radio" class="minimal" name="enableStatus"  value="0" >&nbsp;&nbsp;停用</label>
				</#if>
			</div>
		</div>
		<div class="form-group form-inline row">
			<div class="col-sm-6">
				<label>客户级别:</label>
				<select class="form-control" name="customerLevel">
					<option value="">--请选择--</option>
					<#list customerLevelMap as k,v>
						<option value="${k}" <#if company.customerLevel?? && k==company.customerLevel>selected</#if>>${v}</option>
					</#list>
				</select>
			</div>
			<div class="col-sm-6">
				<label><span style="color: red">*</span>公司员工限制:</label>
				<input class="form-control" type="number" min="1" max="9999" name="employeeMaxNum" value="${company.employeeMaxNum!1}" style="width: 130px;" required />
			</div>
		</div>
		
		<h4 style="padding: 20px 0;border-bottom: 1px solid #e5e5e5">开通版本：</h4>
		<div class="form-group form-inline row">
			<div class="col-sm-12">
				<label>版本：</label>
				<div class="company-version-list">
					<#if company.companyId??>
						<#list companyVersionList as cv>
							<div class="item">
								<input type="hidden" name="cvId" value="${cv.id!}" />
								<select class="form-control" name="versionId" >
									<option value="">--请选择--</option>
									<#list versionList as v>
										<option value="${v.id}" <#if cv.versionId == v.id>selected</#if> >${v.versionName}</option>
									</#list>
								</select>
								<#if cv.activated?? && cv.endTime??>
									<label class="txt">结束时间:</label>
									<input class="form-control calendar-input" type="text" name="endTimeStr" value="<@mymacro.dateFormat cv.endTime "yyyy-MM-dd"></@mymacro.dateFormat>" />
									<label class="txt">剩余时间: ${cv.remainingDays!0}天</label>
								<#else>
									<label class="txt">未激活</label>
								</#if>
								<div class="symbol-box">
									<div class="symbol" onclick="decVersion(this)">
										<div class="row">
											<div class="symbol-dec-left-top"></div>
											<div class="symbol-dec-right-top"></div>
										</div>
										<div class="row">
											<div class="symbol-dec-left-bottom"></div>
											<div class="symbol-dec-right-bottom"></div>
										</div>
									</div>
								</div>
							</div>
						</#list>
					</#if>
				</div>
				<div class="company-version-button" onclick="addVersion()" >
					<span>添加</span>
				</div>
			</div>
		</div>
		
		<h4 style="padding: 20px 0;border-bottom: 1px solid #e5e5e5">管理员账号：</h4>
		<div class="form-group form-inline row">
			<div class="col-sm-6">
				<label><span style="color: red">*</span>管理员姓名：</label>
				<input class="form-control" type="text" name="userName" value="${user.userName!}" maxlength="50"  required />
			</div>
			<div class="col-sm-6">
				<label><span style="color: red">*</span>登录名：</label>
				<#if company.companyId??>
					<input class="form-control" type="text" name="loginName" value="${user.loginName!}" maxlength="50"  readonly="readonly" />
				<#else>
					<input class="form-control" type="text" name="loginName" value="${user.loginName!}" maxlength="50" required />
				</#if>
			</div>
		</div>
		<div class="form-group form-inline row">
			<div class="col-sm-6">
				<label><span style="color: red">*</span>联系电话：</label>
				<input class="form-control" type="text" name="phone" value="${user.phone!}" maxlength="50"   required />
			</div>
			<div class="col-sm-6">
				<label>号码隐藏：</label>
				<#if company.hidePhone??>
					<label class="radio-inline"><input type="radio" name="hidePhone"  value="0" <#if company?? && company.hidePhone?? && company.hidePhone = 0>checked</#if> > 不隐藏</label>
					<label class="radio-inline"><input type="radio" name="hidePhone"  value="1" <#if company?? && company.hidePhone?? && company.hidePhone = 1>checked</#if> > 隐藏</label>
				<#else>
					<label class="radio-inline"><input type="radio" name="hidePhone"  value="0" checked > 不隐藏</label>
					<label class="radio-inline"><input type="radio" name="hidePhone"  value="1" > 隐藏</label>
				</#if>
			</div>
		</div>
</form>

<script>
	$(':input[name="endTimeStr"]').datepicker({
		autoclose: true,
		clearBtn: true,
		format: 'yyyy-mm-dd',
	    language: 'zh-CN'
	});
	$("#addCompany").validate({
        rules: {
            userName : {
            	trimRequired : true,
            	unContainSpace : true
            },
            loginName : {
            	trimRequired : true,
            	unContainSpace : true,
            	loginNameUnique : true
            },
            companyName : {
            	trimRequired : true,
            	unContainSpace : true,
            	companyNameUnique : true
            }
        },
        messages: {
        }
	});
	$.validator.addMethod("trimRequired", function(value, element) {
		if (value == '') {
			return false;
		}
		if ($.trim(value) == '') {
			return false;
		}
		return true;
	}, "该字段不能为空");
	$.validator.addMethod("unContainSpace", function(value, element) {
		if (value == '' || $.trim(value) == '') {
			return true;
		}
		if ($.trim(value).search(/\s/) != -1) {
			return false;
		}
		return true;
	}, "该字段不能包含空格");
	$.validator.addMethod("loginNameUnique", function(value, element) {
		var userId = $("input[name='userId']").val();
		userId = userId ? userId : '';
		var loginName = $.trim(value);
		console.log('userId=' + userId + ', loginName='+loginName);
		
		var verificationPassed = false;
		$.ajax({
			url : "${ctx}/userinfo/verifyLoginNameUnique",
			type : 'post',
			dataType : 'json',
			async : false,
			data : {"userId" : userId, "loginName" : loginName},
			success : function(data) {
				if (data.result == 'success') {
					verificationPassed = true;
				}
			}
		});
		
		return verificationPassed;
	}, "登录名不能重复");
	$.validator.addMethod("companyNameUnique", function(value, element) {
		var companyId = $("input[name='companyId']").val();
		companyId = companyId ? companyId : '';
		var companyName = $.trim(value);
		console.log('companyId=' + companyId + ', companyName='+companyName);
		
		var verificationPassed = false;
		$.ajax({
			url : "${ctx}/company/verifyCompanyNameUnique",
			type : 'post',
			dataType : 'json',
			async : false,
			data : {"companyId" : companyId, "companyName" : companyName},
			success : function(data) {
				console.log('result=' + data.result );
				if (data.result == 'success') {
					verificationPassed = true;
				}
			}
		});
		
		return verificationPassed;
	}, "公司名称不能重复");
	
	$('.select2').select2();
	$.fn.modal.Constructor.prototype.enforceFocus = function() {};
	
	$("select[name='provinceCode']").change(function(){
		var provinceCode = $(this).val();
		$.ajax({
			url:"${ctx}/area/getCity?provinceCode="+provinceCode,
			dataType:"json",
			success:function(res){
				var citys = res.data;
				console.log(citys);
				$("#cityCodeForm").find("option").remove();
				$("#cityCodeForm").append("<option value=''>--请选择--</option>");
				for(var i=0; i<citys.length; i++){
					$("#cityCodeForm").append("<option value='"+citys[i].code+"'>"+citys[i].city+"</option>");
				}
			}
		})
	});
	
	$("select[name='agentsId']").change(function(){
		var agentsName = $(this).find("option:selected").text();
		$("input[name='agentsName']").val(agentsName);
	});
	
	$("select[name='saleId']").change(function() {
		var saleName = $(this).find("option:selected").text();
		$("input[name='saleName']").val(saleName);
	});
	
	$("select[name='accountManagerId']").change(function() {
		var accountManagerName = $(this).find("option:selected").text();
		$("input[name='accountManagerName']").val(accountManagerName);
	});
	
	// 结束时间切换事件 
	$(':input[name="endTimeStr"]').change(function(){
		var endTimeStr = $(this).val();
		var remainingDays = getRemainingDays(endTimeStr);
		
		var txt = $(this).next().text();
		if (txt.indexOf('未激活') == 0) {
			;
		} else {
			$(this).next().text('剩余时间: '+ remainingDays +'天');
		}
	});
	
	/*
	** 计算剩余天数
	** @param {String} str 结束时间，格式yyyy-MM-dd
	*/
	function getRemainingDays(str) {
		var arr = str.split('-');
		// 获取当前时间
		var cal = new Date();
		var now = cal.getTime();
		
		// 重新设置结束时间
		cal.setFullYear(arr[0], arr[1] - 1, arr[2]);
		cal.setHours(23, 59, 59, 999);
		var newEndTime = cal.getTime();
		
		// 计算剩余天数
		var remainingDays = (newEndTime - now) / (1000 * 60 * 60 * 24);
		return remainingDays < 0 ? 0 : Math.ceil(remainingDays);
	}
	
	/* 可选的版本 */
	var versions = {
		<#list versionList as v>
			"${v.id}": "${v.versionName!}",
		</#list>
	};
	
	/*
	** 添加一个版本
	*/
	function addVersion() {
// 		var $items = $(".company-version-list .item");
// 		var length = $items.length;
// 		alert('length=' + length);
		var html = '';
		html += '<div class="item">';
		html += '<select class="form-control" name="versionId" >';
		html += '<option value="">--请选择--</option>';
		// 这里需要循环查询到的可选版本，再放进去。
		for (var key in versions) {
			html += '<option value="'+key+'">' + versions[key] + '</option>';
		}
		html += '</select>';
		html += '<select class="form-control" onchange="versionDurationChange(this);" name="versionDurationType" >';
		html += '<option value="DURATION_MONTH">月</option>';
		html += '<option value="DURATION_DAY">天</option>';
		html += '</select>';
		html += '<div class="duration-input">';
		html += '<input class="form-control" type="text" type="number" maxlength="3" name="versionDuration" />';
		html += '<span>月</span>';
		html += '</div>';
		html += '<div class="symbol-box">';
		html += '<div class="symbol" onclick="decVersion(this)">';
		html += '<div class="row">';
		html += '<div class="symbol-dec-left-top"></div>';
		html += '<div class="symbol-dec-right-top"></div>';
		html += '</div>';
		html += '<div class="row">';
		html += '<div class="symbol-dec-left-bottom"></div>';
		html += '<div class="symbol-dec-right-bottom"></div>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		
		$(".company-version-list").eq(0).append(html);
	}
	/*
	** 删除一个版本
	*/
	function decVersion(obj) {
		$(obj).parent().parent().remove();
	}
	/*
	** 版本时长类型切换
	*/
	function versionDurationChange(obj) {
		var type = $(obj).val();
		if (type == 'DURATION_MONTH') {
			$(obj).next().find("span").text('月');
		} else {
			$(obj).next().find("span").text('天')
		}
	}
</script>
